<template>
  <div class="app-container">
    <span class="version-code">版本 {{ versionCode }}</span>
    <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto" :class="{ disabled: disableAction }">
      <el-form-item prop="chkitemCode">
        <el-input v-model.trim="queryParams.chkitemCode" placeholder="请输入编码" clearable style="width: 130px" />
      </el-form-item>
      <el-form-item prop="chkitemName">
        <el-input v-model.trim="queryParams.chkitemName" placeholder="请输入名称" clearable style="width: 130px" />
      </el-form-item>
      <el-form-item prop="chkitemType">
        <el-select v-model="queryParams.chkitemType" placeholder="检查项类型" clearable style="width: 120px">
          <el-option v-for="dict in dict.type.cq_eval_chkitem_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button size="mini" :icon="isExpand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" @click="handleExpandDebounce">全部{{ isExpand ? '折叠' : '展开' }}</el-button>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="$refs.EditItem.open({ versionId, versionCode }, { treeData: list })" v-if="versionCode">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table class="g-table-tree-expand-align" ref="table" v-loading="listLoading" :data="filteredList" size="small" row-key="chkitemId" :default-expand-all="isExpand" height="calc(100vh - 150px)">
      <el-table-column label="编码" prop="chkitemCode" show-overflow-tooltip min-width="200" class-name="expand-column" />
      <el-table-column label="名称" prop="chkitemName" show-overflow-tooltip min-width="150" />
      <el-table-column label="检查项类型" align="center" width="110">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_chkitem_type" :value="row.chkitemType" v-if="row.chkitemType" />
      </el-table-column>
      <el-table-column label="数据类型" align="center" width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_data_type" :value="row.dataType" v-if="row.dataType" />
      </el-table-column>
      <el-table-column label="得分类型" align="center" show-overflow-tooltip min-width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_score_type" :value="row.scoreType" v-if="row.scoreType" />
      </el-table-column>
      <el-table-column label="事业部统计" align="center" width="80">
        <template slot-scope="{ row }">
          <el-tag v-if="row.isBussCount"><i class="el-icon-check" /></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="城市公司统计" align="center" width="95">
        <template slot-scope="{ row }">
          <el-tag v-if="row.isCityCount"><i class="el-icon-check" /></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="项目统计" align="center" width="80">
        <template slot-scope="{ row }">
          <el-tag v-if="row.isProjectCount"><i class="el-icon-check" /></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="合格项计算" align="center" width="80">
        <template slot-scope="{ row }">
          <el-tag v-if="row.isValidCount"><i class="el-icon-check" /></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优秀项计算" align="center" width="80">
        <template slot-scope="{ row }">
          <el-tag v-if="row.isExceCount"><i class="el-icon-check" /></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="录入方式" align="center" width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_input_mode" :value="row.inputMode" v-if="row.inputMode" />
      </el-table-column>
      <el-table-column label="检查单位" align="center" show-overflow-tooltip min-width="100">
        <span slot-scope="{ row }">{{ row.rdcType | multivalueFilter(dict.label.cq_eval_rdc_type) }}</span>
      </el-table-column>
      <el-table-column label="加减分对象" align="center" show-overflow-tooltip min-width="100">
        <span slot-scope="{ row }">{{ row.addsubObj | multivalueFilter(dict.label.cq_eval_addsub_obj) }}</span>
      </el-table-column>
      <el-table-column label="启用状态" align="center" width="80">
        <div slot-scope="{ row }" @click="toggleIsEnable(row)" style="display: inline-block; cursor: pointer">
          <i class="el-icon-loading" v-if="!!row.isEnableLoading" />
          <el-switch class="g-switch-in" v-model="row.itemIsEnable" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" :width="50" style="pointer-events: none" v-else />
        </div>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="180">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditItem.open(row, { treeData: list })">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)">删除</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-plus" @click="$refs.EditItem.open({ versionId, versionCode, parentId: row.chkitemId }, { treeData: list })">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="$refs.EditCfg.open(row)">配置</el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="routeToStList(row)">标准列表</el-button>
          <router-link slot-scope="{ row }" :to="``" class="link-type">
            <el-button size="mini" type="text" icon="el-icon-setting">标准列表</el-button>
          </router-link>

        </template>
      </el-table-column>
    </el-table>

    <EditItem ref="EditItem" v-model="showEditItem" @ok="getList" />
    <EditCfg ref="EditCfg" v-model="showEditCfg" @ok="getList" />
  </div>
</template>
<script>
// 工程质量-评估-检查项
import { debounce, flatList2tree, isLikeOrEqual } from '@/utils'
import { listChkitem, updateChkitem, delChkitem } from '@/api/checkScore/cqEval'
import EditItemStandard from './components/EditEvalChkitemStandard'
import EditItem from './components/EditEvalChkitem'
import EditCfg from './components/EditEvalChkitemCfg'

export default {
  name: 'EvalChkitem',
  components: { EditItem, EditCfg ,EditItemStandard},
  dicts: ['cq_eval_data_type', 'cq_eval_score_type', 'cq_eval_chkitem_type', 'cq_eval_rdc_type', 'cq_eval_addsub_obj', 'cq_eval_input_mode'],
  filters: {
    multivalueFilter(val, value2label = {}) {
      const str = val || ''
      return str
        .split(',')
        .map(i => value2label[i])
        .filter(i => i)
        .join('、')
    }
  },
  data() {
    return {
      isExpand: true,
      listLoading: false,
      list: [],
      filteredList: [],
      versionId: '',
      versionCode: '',
      queryParams: {
        chkitemCode: '',
        chkitemName: '',
        chkitemType: ''
      },
      showEditItem: false,
      showEditItemStandard: false,
      showEditCfg: false
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    }
  },
  watch: {
    queryParams: {
      deep: true,
      handler() {
        this.handleQueryDebounce()
      }
    }
  },
  created() {
    this.handleQueryDebounce = debounce(this.handleQuery)
    this.handleExpandDebounce = debounce(this.handleExpand)
    this.versionId = this.$route.query?.versionId || ''
    this.versionCode = this.$route.params?.versionCode || ''
    this.getList()
  },
  methods: {
    routeToStList(item){
      this.$router.push(`/checkScore/EditEvalChkitemStandard?versionCode=${item.versionCode}&checkitemCode=${item.chkitemCode}`)

    },
    // 递归切换展开状态
    setChildren(children, expanded) {
      children.map(row => {
        this.$refs.table.toggleRowExpansion(row, expanded)
        if (row.children) this.setChildren(row.children, expanded)
      })
    },
    // 展开/折叠
    handleExpand() {
      this.isExpand = !this.isExpand
      this.setChildren(this.filteredList, this.isExpand)
    },
    async getList() {
      const { versionCode } = this
      if (!versionCode) return this.msgError('参数错误：版本号不能为空')

      const opt = { ...this.queryParams, versionCode }
      this.listLoading = true
      const res = await listChkitem(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      let data = res.data || []
      data.map(i => {
        i.isEnableLoading = false
        i.removeLoading = false
      })
      data = flatList2tree(data, { id: 'chkitemId' })
      this.list = data
      this.handleQuery()
    },
    handleQuery() {
      // 本地树形搜索
      const { chkitemCode, chkitemName, chkitemType } = this.queryParams
      const opts = { like: { chkitemCode, chkitemName }, eq: { chkitemType } }
      const list = JSON.parse(JSON.stringify(this.list))
      const recursion = list =>
        list.filter(item => {
          if (item.children?.length) item.children = recursion(item.children)
          return isLikeOrEqual(item, opts) || item.children?.length
        })
      const data = recursion(list)
      this.filteredList = data
      this.isExpand = true
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.getList()
    },
    async toggleIsEnable(item) {
      const isEnable = item.itemIsEnable ? 0 : 1
      const name = isEnable === 1 ? '启用' : '禁用'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { ...item, isEnable }
      item.isEnableLoading = true
      const res = await updateChkitem(opt).catch(() => false)
      item.isEnableLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    async handleDelete(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确认删除"${item.chkitemName}"?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delChkitem(item.chkitemId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    }
  },

}
</script>
<style lang="scss" scoped>
.version-code {
  position: absolute;
  font-size: 14px;
  right: 12px;
  top: 12px;
  color: #909399;
}
</style>
